package com.tdt.alarm.controller.fragment;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.tdt.alarm.R;
import com.tdt.alarm.controller.AddAlarm;
import com.tdt.alarm.controller.CheckAlarmService;
import com.tdt.alarm.controller.OneShotAlarm;
import com.tdt.alarm.controller.RepeatService;
import com.tdt.alarm.model.AlarmDBHelper;
import com.tdt.alarm.model.MyArrayAdapter;
import com.tdt.alarm.model.SetAlarm;
import com.tdt.alarm.model.Time;
import com.tdt.alarm.model.Utils;
import com.tdt.alarm.model.seekbar.SeekArc;
import com.tdt.alarm.model.seekbar.SeekArc.OnSeekArcChangeListener;

public class Home extends Fragment implements OnItemClickListener {
	List<SetAlarm> arrAlarm;
	MyArrayAdapter adapter = null;
	ListView listAlarm = null;
	Button addAlarm;
	Button btnSetting;
	Button btnTimer;
	Button btnReminder;
	CheckBox cbActive;
	static TextView tvday;
	private static SeekArc mSeekArcMin;
	private static SeekArc mSeekArcHour;
	private TextView mSeekArcMinProgress;
	private TextView mSeekArcHourProgress;
	View layoutTime;
	// SetAlarm currentAlarm = new SetAlarm();
	AlarmDBHelper alarmDB;
	Context context;
	Toast mToast;

	Intent Mringtone;
	Ringtone rt;
	RingtoneManager mRingtoneManager;

	// use for edit mode
	static boolean isEditMode;
	static SetAlarm currentAlarm = new SetAlarm();

	List<SetAlarm> alist;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// return inflater.inflate(R.layout.activity_alarm, container, false);
		context = getActivity().getApplicationContext();
		View view = inflater.inflate(R.layout.activity_alarm, container, false);

		addAlarm = (Button) view.findViewById(R.id.btnAddAlarm);
		listAlarm = (ListView) view.findViewById(R.id.listViewListAlarm);
		btnSetting = (Button) view.findViewById(R.id.btnSetting);
		btnTimer = (Button) view.findViewById(R.id.btnTimer);
		btnReminder = (Button) view.findViewById(R.id.btnReminder);
		cbActive = (CheckBox) view.findViewById(R.id.chkActive);
		layoutTime = view.findViewById(R.id.layoutTime);
		// tvday = (TextView) view.findViewById(R.id.tvday);

		arrAlarm = new ArrayList<SetAlarm>();
		adapter = new MyArrayAdapter(this.getActivity(),
				R.layout.custom_list_alarm, arrAlarm, listAlarm);
		listAlarm.setAdapter(adapter);
		currentAlarm = new SetAlarm();
		alarmDB = new AlarmDBHelper(context);
		isEditMode = false;

		addAlarm();
		// xử lý báo chuông khi không có sự kiến nhấn nào
		// if (Utils.countActiveCurrent(arrAlarm) > 0) {
		// setOneShowAlarm(null, Utils.getAlarmActiveFirst(arrAlarm), arrAlarm);
		// }

		listAlarm.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int position, long arg3) {
			}
		});

		addAlarm.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				// addAlarm();
				// setOneShowAlarm(null,1);
				Intent intent = new Intent(getActivity(), AddAlarm.class);
				startActivity(intent);
				getActivity().finish();
			}
		});

		mSeekArcMin = (SeekArc) view.findViewById(R.id.seekArcMin);
		mSeekArcHour = (SeekArc) view.findViewById(R.id.seekArcHour);

		mSeekArcMinProgress = (TextView) view
				.findViewById(R.id.seekArcMinProgress);
		mSeekArcHourProgress = (TextView) view
				.findViewById(R.id.seekArcHourProgress);

		// Set font
		Typeface tf = Typeface.createFromAsset(getActivity().getAssets(),
				"digital_7.ttf");
		mSeekArcHourProgress.setTypeface(tf);
		mSeekArcMinProgress.setTypeface(tf);

		mSeekArcMin.setmMax(60);
		mSeekArcMin.setArcRotation(0);
		mSeekArcMin.setStartAngle(0);
		mSeekArcMin.setSweepAngle(360);
		mSeekArcMin.setArcWidth(1);
		mSeekArcMin.setProgressWidth(16);
		mSeekArcMin.setRoundedEdges(true);
		mSeekArcMin.setTouchInSide(true);
		mSeekArcMin.setClockwise(true);

		mSeekArcHour.setmMax(24);
		mSeekArcHour.setArcRotation(0);
		mSeekArcHour.setStartAngle(0);
		mSeekArcHour.setSweepAngle(360);
		mSeekArcHour.setArcWidth(1);
		mSeekArcHour.setProgressWidth(16);
		mSeekArcHour.setRoundedEdges(true);
		mSeekArcHour.setTouchInSide(true);
		mSeekArcHour.setClockwise(true);

		mSeekArcMin.setOnSeekArcChangeListener(new OnSeekArcChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekArc seekArc) {
			}

			@Override
			public void onStartTrackingTouch(SeekArc seekArc) {
			}

			@Override
			public void onProgressChanged(SeekArc seekArc, int progress,
					boolean fromUser) {
				progress %= 60;
				String text = "";
				if (progress < 10) {
					text = "0" + progress;
				} else {
					text = progress + "";
				}
				mSeekArcMinProgress.setText(text);
			}
		});

		mSeekArcHour.setOnSeekArcChangeListener(new OnSeekArcChangeListener() {

			@Override
			public void onStopTrackingTouch(SeekArc seekArc) {
			}

			@Override
			public void onStartTrackingTouch(SeekArc seekArc) {
			}

			@Override
			public void onProgressChanged(SeekArc seekArc, int progress,
					boolean fromUser) {
				progress %= 24;
				String text = "";
				if (progress < 10) {
					text = "0" + progress;
				} else {
					text = progress + "";
				}
				mSeekArcHourProgress.setText(text);
			}
		});

		// set click on layout time
		layoutTime.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				int hour;
				// if (!isAM) {
				// hour = Integer.parseInt((String) mSeekArcHourProgress
				// .getText()) + 12;
				// } else {
				// hour = Integer.parseInt((String) mSeekArcHourProgress
				// .getText());
				// }

				hour = Integer.parseInt((String) mSeekArcHourProgress.getText());
				int min = Integer.parseInt((String) mSeekArcMinProgress
						.getText());
				Time time = new Time(hour, min, 0);
				currentAlarm.setTime(time);
				
				if (!isEditMode) {

					// RingtoneManager mRingtoneManager = new
					// RingtoneManager(context);
					// mRingtoneManager.setType(RingtoneManager.TYPE_RINGTONE);
					//
					// int length = mRingtoneManager.getCursor().getCount();
					// Uri uri = mRingtoneManager.getRingtoneUri(0);
					currentAlarm.setCheckActive(true);

					// Utils.writeAlarmToFile(alarm);
					// change to DB
					alarmDB.createAlarm(currentAlarm);
				} else {
					alarmDB.updateAlarm(currentAlarm);
					addAlarm();
					isEditMode = false;
				}
				addAlarm();
				currentAlarm = new SetAlarm();
			}
		});

		layoutTime.setOnLongClickListener(new OnLongClickListener() {

			@Override
			public boolean onLongClick(View v) {
				onClickRepeate();
				return false;
			}
		});

		return view;

	}

	// public void itemClick(int pos) {
	// Toast.makeText(this.getActivity(), "đã nhấn vào " + pos,
	// Toast.LENGTH_SHORT).show();
	// Intent intenItem = new Intent(this.getActivity(), Set_Alarm.class);
	// startActivity(intenItem);
	//
	// }

	public void addAlarm() {
		arrAlarm = alarmDB.getAlarms();
		adapter.clear();
		if (arrAlarm != null) {
			adapter.addAll(arrAlarm);
		}
		adapter.notifyDataSetChanged();
		
		Intent i = new Intent(getActivity(), CheckAlarmService.class);
		getActivity().startService(i);

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

//		Toast.makeText(getActivity(), "Hello " + position, Toast.LENGTH_SHORT)
//				.show();

	}

	// cài đặt th�?i gian để đồng hồ kêu chuông
	public void setOneShowAlarm(Calendar alarmPoint, int position,
			List<SetAlarm> list) {
		Intent intent = new Intent(this.getActivity(), OneShotAlarm.class);
		PendingIntent sender = PendingIntent.getBroadcast(this.getActivity(),
				0, intent, 0);
		SetAlarm alarm = Utils.getCurrentAlarm(position, list);
		Toast.makeText(
				getActivity(),
				"next alarm home: " + alarm.getTime().getHour() + ":"
						+ alarm.getTime().getMinute(), Toast.LENGTH_SHORT)
				.show();
		tvday.setText("Next alarm set for " + alarm.getTime().getHour() + ":"
				+ alarm.getTime().getMinute());
		alarmPoint = Calendar.getInstance();
		alarmPoint.set(2015, 10, 27, alarm.getTime().getHour(), alarm.getTime()
				.getMinute());

		Calendar calendar = Calendar.getInstance();

		int distance = alarmPoint.get(Calendar.HOUR) * 3600
				+ alarmPoint.get(Calendar.MINUTE) * 60
				- calendar.get(Calendar.HOUR) * 3600
				- calendar.get(Calendar.MINUTE) * 60
				- calendar.get(Calendar.SECOND);
		if (distance < 0)
			distance += 86400;

		calendar.add(Calendar.SECOND, distance);

		// Schedule the alarm!
		AlarmManager am = (AlarmManager) getActivity().getApplicationContext()
				.getSystemService(Context.ALARM_SERVICE);
		am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), sender);

		// Tell the user about what we did.
		if (mToast != null) {
			mToast.cancel();
		}
//		mToast = Toast.makeText(this.getActivity(), "Next alarm in: "
//				+ distance + "s", Toast.LENGTH_SHORT);
//		mToast.show();
	}

	public static void findNearlyAlarm(int position, List<SetAlarm> list) {
		SetAlarm alarm = Utils.getCurrentAlarm(position, list);
		tvday.setText("Next alarm set for " + alarm.getTime().getHour() + ":"
				+ alarm.getTime().getMinute());
	}

	@Override
	public void onStart() {
		super.onStart();
		// if (Utils.countActiveCurrent(arrAlarm) > 0) {
		// setOneShowAlarm(null, Utils.getAlarmActiveFirst(arrAlarm), arrAlarm);
		// }
		// context.startService(new
		// Intent(context.getApplicationContext(),CheckAlarmService.class));
		Intent i2 = new Intent(getActivity(), RepeatService.class);
		getActivity().startService(i2);
		
//		Intent i = new Intent(getActivity(), CheckAlarmService.class);
//		getActivity().startService(i);
		
		
	}

	public static void editAlarm(SetAlarm setAlarm) {
		isEditMode = true;
		int hour = setAlarm.getTime().getHour();
		int minute = setAlarm.getTime().getMinute();
		mSeekArcHour.setProgress(hour);
		mSeekArcMin.setProgress(minute);
		currentAlarm = setAlarm;
	}

	public void onClickRepeate() {
		AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
		builder.setTitle("Advanced");
		// builder.setMessage("Are you sure you want to delete this entry?");
		LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
		View promptView = layoutInflater.inflate(R.layout.set_alarm_repeat,
				null);
		builder.setView(promptView);

		final CheckBox cbWeekly = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_weekly);
		final CheckBox cb2 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_monday);
		final CheckBox cb3 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_tuesday);
		final CheckBox cb4 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_wednesday);
		final CheckBox cb5 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_thursday);
		final CheckBox cb6 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_friday);
		final CheckBox cb7 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_saturday);
		final CheckBox cb8 = (CheckBox) promptView
				.findViewById(R.id.alarm_details_repeat_sunday);
		final TextView textViewName = (TextView) promptView
				.findViewById(R.id.alarm_details_name);
		final TextView textViewRingtoneSelection = (TextView) promptView
				.findViewById(R.id.alarm_label_tone_selection);
		final Switch switchActive = (Switch) promptView
				.findViewById(R.id.switchActive);

		final View ringtoneLayout = promptView
				.findViewById(R.id.alarm_ringtone_container);
		ringtoneLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onClickRingtone(v);
				Ringtone ringtone = RingtoneManager.getRingtone(context,
						currentAlarm.getRingtone());
				textViewRingtoneSelection.setText(ringtone.getTitle(context));
			}
		});

		if (isEditMode) {
			cbWeekly.setChecked(currentAlarm.isRepeatWeekly());
			cb2.setChecked(currentAlarm.getRepeatingDay(1));
			cb3.setChecked(currentAlarm.getRepeatingDay(2));
			cb4.setChecked(currentAlarm.getRepeatingDay(3));
			cb5.setChecked(currentAlarm.getRepeatingDay(4));
			cb6.setChecked(currentAlarm.getRepeatingDay(5));
			cb7.setChecked(currentAlarm.getRepeatingDay(6));
			cb8.setChecked(currentAlarm.getRepeatingDay(0));
			textViewName.setText(currentAlarm.getLabel());
			if (currentAlarm.getRingtone() != null) {
				Ringtone ringtone = RingtoneManager.getRingtone(context,
						currentAlarm.getRingtone());
				textViewRingtoneSelection.setText(ringtone.getTitle(context));
			}
			switchActive.setChecked(currentAlarm.isCheckActive());
		}

		builder.setPositiveButton(android.R.string.yes,
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {

						// if(isEditMode){
						// currentAlarm.setRepeatingDay(1, cb2.isChecked());
						// currentAlarm.setRepeatingDay(2, cb3.isChecked());
						// currentAlarm.setRepeatingDay(3, cb4.isChecked());
						// currentAlarm.setRepeatingDay(4, cb5.isChecked());
						// currentAlarm.setRepeatingDay(5, cb6.isChecked());
						// currentAlarm.setRepeatingDay(6, cb7.isChecked());
						// currentAlarm.setRepeatingDay(0, cb8.isChecked());
						// currentAlarm.setRepeatWeekly(cbWeekly.isChecked());
						// currentAlarm.setLabel(textViewName.getText().toString());
						// } else {
						currentAlarm.setRepeatingDay(1, cb2.isChecked());
						currentAlarm.setRepeatingDay(2, cb3.isChecked());
						currentAlarm.setRepeatingDay(3, cb4.isChecked());
						currentAlarm.setRepeatingDay(4, cb5.isChecked());
						currentAlarm.setRepeatingDay(5, cb6.isChecked());
						currentAlarm.setRepeatingDay(6, cb7.isChecked());
						currentAlarm.setRepeatingDay(0, cb8.isChecked());
						currentAlarm.setRepeatWeekly(cbWeekly.isChecked());
						currentAlarm
								.setLabel(textViewName.getText().toString());
						currentAlarm.setCheckActive(switchActive.isChecked());
						// }

					}
				})
				.setNegativeButton(android.R.string.no,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								// do nothing
							}
						})
				// .setIcon(android.R.drawable.ic_dialog_alert)
				.show();
	}

	@SuppressWarnings("deprecation")
	public void onClickRingtone(View arg0) {
		// TODO Auto-generated method stub
		// Starts the intent or Activity of the ringtone manager, opens popup
		// box
		Mringtone = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);

		// specifies what type of tone we want, in this case "ringtone", can be
		// notification if you want
		Mringtone.putExtra(RingtoneManager.EXTRA_RINGTONE_TYPE,
				RingtoneManager.TYPE_RINGTONE);

		// gives the title of the RingtoneManager picker title
		Mringtone.putExtra(RingtoneManager.EXTRA_RINGTONE_TITLE,
				"Ringtone Picker!");

		// returns true shows the rest of the song on the device in the default
		// location
		Mringtone.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_INCLUDE_DRM,
				true);

		Uri uri = currentAlarm.getRingtone();
		// chooses and keeps the selected item as a uri
		if (uri != null) {
			Mringtone
					.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI, uri);
		} else {
			Mringtone.putExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI,
					(Uri) null);
		}

		startActivityForResult(Mringtone, 0);

	}

	public void onActivityResult(int requestCode, int resultCode,
			Intent Mringtone) {
		switch (resultCode) {
		/*
*/

		case Activity.RESULT_OK:
			// sents the ringtone that is picked in the Ringtone Picker Dialog
			Uri uri = Mringtone
					.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);

			// send the output of the selected to a string
			// String test = uri.toString();
			// Toast.makeText(getActivity(), test, Toast.LENGTH_SHORT).show();
			currentAlarm.setRingtone(uri);
			stop();
			// the program creates a "line break" when using the "\n" inside a
			// string value
			// text.setText("\n " + test + "\n " + title);

			// prints out the result in the console window
			Log.i("Sample", "uri " + uri);

			// inserts another line break for more data, this times adds the
			// cursor count on the selected item
			// text.append("\n " + mcursor.getCount());

			// set default ringtone
			try {
				RingtoneManager.setActualDefaultRingtoneUri(getActivity(),
						resultCode, uri);
			} catch (Exception localException) {

			}
			break;

		}

	}

	// stop ringtone play
	private void stop() {
		if (rt != null) {
			rt.stop();
		}
	}
	
	public void getListWeek(){
	}

}
